package com.cloud.base.proxy;

import com.alibaba.fastjson.JSON;
import com.cloud.base.annotation.ApiMapping;
import com.cloud.base.annotation.ApiProxy;
import com.cloud.base.bean.OpenConfig;
import com.cloud.base.type.RequestFormat;
import com.cloud.base.utils.ApiUtils;
import com.cloud.base.utils.GetBeanUtils;
import com.common.utils.tools.ObjectUtils;
import com.common.utils.tools.http.HttpUtils;
import com.common.utils.tools.pay.WXPayUtil;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpMethod;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Map;


public class ApiRequest implements Request, Serializable {

    final OpenConfig config;
    final Method method;
    final ApiMapping apiMapping;
    final ApiProxy apiProxy;

    ApiRequest(ApiProxy apiProxy, Method method, OpenConfig config) {
        this.config = config;
        this.method = method;
        this.apiMapping = AnnotationUtils.findAnnotation(method, ApiMapping.class);
        this.apiProxy = apiProxy;
    }

    @Override
    public String request(Serializable param) throws Exception {
        String requestUrl = ApiUtils.getRequestUrl(apiProxy, apiMapping);
        if (HttpMethod.GET.equals(apiMapping.method())) {
            Map<String, String> requestParam = ObjectUtils.toMapStr(param);
            return HttpUtils.get(requestUrl, requestParam, "UTF-8");
        } else if (HttpMethod.POST.equals(apiMapping.method())) {
            Map<String, String> requestParam;
            Class<?> beanClass = apiProxy.requestClass();
            RequestFormat format = apiMapping.format();
            Map<String, String> needBuildParam = ObjectUtils.toMapStr(param);
            String typeName = beanClass.getTypeName();
            if(typeName.equals(Void.class.getTypeName())){
                requestParam = needBuildParam;
            }else {
                RequestHandler requestHandler = (RequestHandler)GetBeanUtils.getBean(beanClass.getName());
                requestParam = requestHandler.buildRequestParam(needBuildParam, config);

            }
            if (RequestFormat.JSON.equals(format)) {
                String json = JSON.toJSONString(requestParam);
                return HttpUtils.requestJson(requestUrl, null, json, "UTF-8");
            } else if (RequestFormat.XML.equals(format)) {
                String xml = WXPayUtil.mapToXml(requestParam);
            }

        }
        return null;
    }


}
